package org.foreningsgatan.modules.glcore.graphics;

import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

public class TexturePacker {
	private static final int WIDTH = 1024;
	private static final int HEIGHT = 1024;
	
	private BufferedImage mImage;
	private int mCurrentX;
	private int mCurrentY;
	private int mCurrentRowHeight;
	
	public TexturePacker() {
		mImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
		mCurrentRowHeight = 0;
		mCurrentX = 0;
		mCurrentY = 0;
	}
	
	public boolean hasRoom(BufferedImage pImage) {
		int vInputWidth = pImage.getWidth();
		int vInputHeight = pImage.getHeight();
		
		if ((vInputWidth > WIDTH) || (vInputHeight > HEIGHT)) {
			return false;
		}
		
		if (mCurrentX + vInputWidth > WIDTH) {
			return mCurrentY + mCurrentRowHeight + vInputHeight <= HEIGHT;
		} else {
			return mCurrentY + vInputHeight <= HEIGHT;
		}
	}
	
	public Rectangle2D.Float add(BufferedImage pImage) {
		int vInputWidth = pImage.getWidth();
		int vInputHeight = pImage.getHeight();
		
		if (mCurrentX + vInputWidth > WIDTH) {
			mCurrentX = 0;
			mCurrentY += mCurrentRowHeight;
			mCurrentRowHeight = vInputHeight;
		} else {
			if (pImage.getHeight() > mCurrentRowHeight) {
				mCurrentRowHeight = vInputHeight;
			}
		}
		
		Graphics2D g = (Graphics2D) mImage.getGraphics();
		g.drawImage(pImage, mCurrentX, mCurrentY, null);
		
		mCurrentX += vInputWidth;
		
		return new Rectangle2D.Float(
				(float) (mCurrentX - vInputWidth) / WIDTH, 
				(float) mCurrentY / HEIGHT, 
				(float) vInputWidth / WIDTH, 
				(float) vInputHeight / HEIGHT);
	}
	
	public BufferedImage getResult() {
		return mImage;
	}
}
